package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        // 当前集合用于封装日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.isAfter(end)) {
            // 日期加一
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 营业额集合
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // 查询营业额对应的营业数据,营业额是指:状态为已完成的订单金额
            LocalDateTime beginTime =LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover=turnover==null?0.0:turnover;
            turnoverList.add(turnover);
        }

        String turnoverListStr= StringUtil.join(",",turnoverList);
        String dateListStr= StringUtil.join(",", dateList);
        return TurnoverReportVO.builder()
                .turnoverList(turnoverListStr)
                .dateList(dateListStr)
                .build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
         // 当前集合用于封装日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.isAfter(end)) {
            // 日期加一
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //每天用户总数集合
        List<Integer> totalUserList = new ArrayList<>();
        //每天新用户集合
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //
            LocalDateTime beginTime =LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("endTime",endTime);
            Integer totalUser = userMapper.countByMap(map);
            totalUserList.add(totalUser);
            map.put("beginTime",beginTime);
            Integer newUser = userMapper.countByMap(map);
            newUserList.add(newUser);
        }
        String dateListStr= StringUtil.join(",", dateList);
        String totalUserListStr= StringUtil.join(",",totalUserList);
        String newUserListStr= StringUtil.join(",",newUserList);

        return UserReportVO.builder()
                .dateList(dateListStr)
                .totalUserList(totalUserListStr)
                .newUserList(newUserListStr)
                .build();
    }

    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //用于封装日期集合
        List<LocalDate> dateList = new ArrayList<>();
        while(!begin.isAfter(end)){
            dateList.add(begin);
            begin=begin.plusDays(1);
        }
        //用于封装订单总数集合
        List<Integer> totalOrderCountList = new ArrayList<>();
        //用于封装有效订单集合
        List<Integer> validOrderCountList = new ArrayList<>();
        //订单总数
        Integer totalOrderCount=0;
        //有效订单总数
        Integer validOrderCount=0;

        for (LocalDate date : dateList) {
            LocalDateTime beginTime=LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date, LocalTime.MAX);
            //查询订单总数
            Map<String,Object> map=new HashMap<>();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            Integer totalCount=orderMapper.countByMap(map);
            map.put("status",Orders.COMPLETED);
            Integer validCount=orderMapper.countByMap(map);
            totalOrderCount+=totalCount;
            validOrderCount+=validCount;
            totalOrderCountList.add(totalCount);
            validOrderCountList.add(validCount);
            //查询有效订单数
        }
          //订单完成率
        Double orderCompletionRate=0.0;
        if(totalOrderCount!=0){
             orderCompletionRate=  (validOrderCount.doubleValue() /totalOrderCount);
        }
        String dateListStr= StringUtil.join(",",dateList);
        String totalOrderCountListStr= StringUtil.join(",",totalOrderCountList);
        String validOrderCountListStr= StringUtil.join(",",validOrderCountList);
        return OrderReportVO.builder()
                .orderCompletionRate(orderCompletionRate)
                .validOrderCount(validOrderCount)
                .totalOrderCount(totalOrderCount)
                .dateList(dateListStr)
                .orderCountList(totalOrderCountListStr)
                .validOrderCountList(validOrderCountListStr)
                .build();
    }

    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime=LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime=LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOS=orderMapper.getSalesTop10(beginTime,endTime);
//        List<String> nameList=new ArrayList<>();
//        List<String> numberList=new ArrayList<>();
//        goodsSalesDTOS.forEach(
//                goodsSalesDTO -> {
//                    nameList.add(goodsSalesDTO.getName());
//                    numberList.add(goodsSalesDTO.getNumber().toString());
//                }
//        );
        String nameList=goodsSalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.joining(","));
        String numberList=goodsSalesDTOS.stream().map(goodsSalesDTO -> goodsSalesDTO.getNumber().toString()).collect(Collectors.joining(","));
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) throws IOException {
        //1.查询营业额数据 30天的运营数据
//        LocalDate.now().minusDays(30);
        LocalDate DataBegin=LocalDate.now().plusDays(-30);
        LocalDate DataEnd=LocalDate.now().plusDays(-1);
        LocalDateTime beginTime=LocalDateTime.of(DataBegin, LocalTime.MIN);
        LocalDateTime endTime=LocalDateTime.of(DataEnd, LocalTime.MAX);
        BusinessDataVO businessDataVO=workspaceService.getBusinessData(beginTime,endTime);

        //2.用过POI将数据写到Excel文件中

        //类加载器默认是从classPath路径(resource)加载资源。
        //InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream("xx.properties");
        //当前类的URI目录，不包括自己 要加载的资源路径与当前类所在包的路径一致
        //Class.getResourceAsStream("");
        //当前的classpath的绝对URI路径 要加载的资源路径在resources下
        //Class.getResourceAsStream("/");

        InputStream in=this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try{
            if (in != null) {
                XSSFWorkbook workbook=new XSSFWorkbook(in);
                //获取第一个sheet页
                XSSFSheet sheet=workbook.getSheet("Sheet1");
                //填充数据---时间
                sheet.getRow(1).getCell(1).setCellValue(DataBegin+"至"+DataEnd);
                XSSFRow row = sheet.getRow(3);
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());
                row = sheet.getRow(4);
                row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

                //填充明细数据
                for (int i = 0; i < 30; i++){
                    LocalDate date = DataBegin.plusDays(i);
                    LocalDateTime dateBeginTime = LocalDateTime.of(date, LocalTime.MIN);
                    LocalDateTime dateEndTime = LocalDateTime.of(date, LocalTime.MAX);
                    BusinessDataVO balanceDataVO = workspaceService.getBusinessData(dateBeginTime,dateEndTime);
                    row = sheet.getRow(7+i);
                    row.getCell(1).setCellValue(date.toString());
                    row.getCell(2).setCellValue(balanceDataVO.getTurnover());
                    row.getCell(3).setCellValue(balanceDataVO.getValidOrderCount());
                    row.getCell(4).setCellValue(balanceDataVO.getOrderCompletionRate());
                    row.getCell(5).setCellValue(balanceDataVO.getUnitPrice());
                    row.getCell(6).setCellValue(balanceDataVO.getNewUsers());
                }


                 //3.将Excel文件下载到客户端浏览器
                //getOutputStream()       和        getWriter这两个方法互相排斥，
                //用于输出字符流数据或者二进制的字节流数据  处理字符流数据
                //响应调用getOutputStream()方法，输出的二进制流数据只适用于ISO 8859-1编码，所以在输出中文的时候会报500错误。
                //调用了其中的任何一个方法后，就不能调用另外一个
                // response.setContentType("text/html;charset=utf-8");
                //可以重复调用此方法以更改内容类型和字符编码。可以在客户端中正确显示中文
                ServletOutputStream out = response.getOutputStream();
                workbook.write(out);
                out.close();
                workbook.close();
            }
        }catch (IOException ignored){

        }

    }
}
